import React, { useState, useRef, useEffect } from 'react';
import { Card, Typography, Upload, Button, List, Space, message, Progress, Tag } from 'antd';
import { UploadOutlined, FolderOpenOutlined, DeleteOutlined, FileTextOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import type { UploadProps, UploadFile } from 'antd';
import { fileSystemService } from '../services/fileSystemService';
创建一个功能页面，拖入一个文件夹或者是多个文件，将文件夹中的文件名中文和空格删除
const { Title, Text, Paragraph } = Typography;
const { Dragger } = Upload;

interface FileItem {
  id: string;
  name: string;
  originalName: string;
  path?: string;
  status: 'pending' | 'processing' | 'success' | 'error';
  error?: string;
}

const FileNameProcessor: React.FC = () => {
  const [files, setFiles] = useState<FileItem[]>([]);
  const [processing, setProcessing] = useState(false);
  const [processedCount, setProcessedCount] = useState(0);
  const [isTauriEnvironment, setIsTauriEnvironment] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setIsTauriEnvironment(fileSystemService.isTauriEnvironment());
  }, []);

  // 删除文件名中的中文和空格
  const sanitizeFileName = (fileName: string): string => {
    // 分离文件名和扩展名
    const lastDotIndex = fileName.lastIndexOf('.');
    let nameWithoutExt = fileName;
    let extension = '';
    
    if (lastDotIndex !== -1) {
      nameWithoutExt = fileName.substring(0, lastDotIndex);
      extension = fileName.substring(lastDotIndex);
    }
    
    // 移除非ASCII字符（中文）和空格
    const sanitizedName = nameWithoutExt.replace(/[\u4e00-\u9fa5\s]/g, '');
    
    // 如果处理后文件名变空，则使用默认名称
    return sanitizedName || 'unnamed' + extension;
  };

  // 处理单个文件
  const processFile = async (file: FileItem): Promise<FileItem> => {
    try {
      // 在真实环境中，这里应该调用文件系统API重命名文件
      // 目前仅模拟处理
      const updatedFile = {
        ...file,
        status: 'success' as const,
        name: sanitizeFileName(file.name)
      };
      
      // 在Tauri环境中可以实现真实的文件重命名
      if (isTauriEnvironment && file.path) {
        try {
          const tauri = (window as any).__TAURI__;
          const fs = tauri.fs;
          const path = tauri.path;
          
          const directory = await path.dirname(file.path);
          const newPath = await path.join(directory, updatedFile.name);
          
          await fs.renameFile({
            oldPath: file.path,
            newPath: newPath
          });
          
          updatedFile.path = newPath;
        } catch (error) {
          console.error('重命名文件失败:', error);
          updatedFile.status = 'error';
          updatedFile.error = error instanceof Error ? error.message : '重命名失败';
        }
      }
      
      return updatedFile;
    } catch (error) {
      return {
        ...file,
        status: 'error' as const,
        error: error instanceof Error ? error.message : '处理失败'
      };
    }
  };

  // 处理所有文件
  const processAllFiles = async () => {
    if (files.length === 0) {
      message.warning('请先添加文件');
      return;
    }

    setProcessing(true);
    setProcessedCount(0);

    try {
      const updatedFiles = [...files];
      
      for (let i = 0; i < updatedFiles.length; i++) {
        updatedFiles[i].status = 'processing';
        setFiles([...updatedFiles]);
        
        updatedFiles[i] = await processFile(updatedFiles[i]);
        setFiles([...updatedFiles]);
        setProcessedCount(i + 1);
      }
      
      const successCount = updatedFiles.filter(f => f.status === 'success').length;
      message.success(`成功处理 ${successCount}/${files.length} 个文件`);
    } finally {
      setProcessing(false);
    }
  };

  // 处理拖入的文件
  const handleFileDrop = (info: { fileList: UploadFile[] }) => {
    const newFiles: FileItem[] = info.fileList.map((file, index) => ({
      id: `file-${Date.now()}-${index}`,
      name: file.name,
      originalName: file.name,
      status: 'pending',
      // 在浏览器环境中，我们无法获取文件的真实路径
    }));
    
    setFiles([...files, ...newFiles]);
  };

  // 选择文件夹
  const handleFolderSelect = async () => {
    if (!isTauriEnvironment) {
      message.info('文件夹选择功能仅在桌面应用中可用');
      return;
    }

    try {
      const tauri = (window as any).__TAURI__;
      const dialog = tauri.dialog;
      const fs = tauri.fs;
      const path = tauri.path;

      // 打开文件夹选择对话框
      const folderPath = await dialog.open({
        directory: true,
        multiple: false,
      });

      if (!folderPath) return;

      // 读取文件夹内容
      const entries = await fs.readDir({
        dir: folderPath,
        recursive: false,
      });

      // 过滤出文件（非文件夹）
      const newFiles: FileItem[] = await Promise.all(
        entries
          .filter((entry: any) => entry.type === 'file')
          .map(async (entry: any, index: number) => {
            const fullPath = await path.join(folderPath, entry.name);
            return {
              id: `folder-file-${Date.now()}-${index}`,
              name: entry.name,
              originalName: entry.name,
              path: fullPath,
              status: 'pending',
            };
          })
      );

      setFiles([...files, ...newFiles]);
      message.success(`已添加 ${newFiles.length} 个文件`);
    } catch (error) {
      console.error('选择文件夹失败:', error);
      message.error('选择文件夹失败: ' + (error instanceof Error ? error.message : String(error)));
    }
  };

  // 清空文件列表
  const clearFiles = () => {
    setFiles([]);
    setProcessedCount(0);
  };

  // 上传配置
  const uploadProps: UploadProps = {
    name: 'files',
    multiple: true,
    beforeUpload: (file) => {
      // 阻止自动上传，仅添加到列表中
      return false;
    },
    fileList: [],
    onChange: handleFileDrop,
    showUploadList: false,
  };

  // 渲染文件状态标签
  const renderStatusTag = (file: FileItem) => {
    switch (file.status) {
      case 'success':
        return <Tag color="success"><CheckCircleOutlined /> 成功</Tag>;
      case 'error':
        return <Tag color="error"><CloseCircleOutlined /> 失败</Tag>;
      case 'processing':
        return <Tag color="processing">处理中</Tag>;
      default:
        return <Tag>等待处理</Tag>;
    }
  };

  return (
    <Card className="fileNameProcessor-card" style={{ margin: '20px' }}>
      <Title level={4}>文件名处理工具</Title>
      <Paragraph>拖入文件夹或多个文件，将自动删除文件名中的中文和空格</Paragraph>
      
      <div style={{ marginBottom: '20px' }}>
        <Dragger {...uploadProps}>
          <p className="ant-upload-drag-icon">
            <UploadOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">
            支持单个或批量上传
          </p>
        </Dragger>
        
        {isTauriEnvironment && (
          <Button 
            type="primary" 
            icon={<FolderOpenOutlined />} 
            onClick={handleFolderSelect}
            style={{ marginTop: '10px' }}
          >
            选择文件夹
          </Button>
        )}
      </div>

      {files.length > 0 && (
        <div>
          <Space style={{ marginBottom: '10px' }}>
            <Button 
              type="primary" 
              onClick={processAllFiles}
              disabled={processing}
            >
              处理文件名
            </Button>
            <Button 
              danger 
              icon={<DeleteOutlined />} 
              onClick={clearFiles}
              disabled={processing}
            >
              清空
            </Button>
          </Space>
          
          {processing && (
            <Progress 
              percent={(processedCount / files.length) * 100} 
              status="active" 
              style={{ marginBottom: '15px' }}
            />
          )}

          <List
            bordered
            dataSource={files}
            renderItem={(file) => (
              <List.Item
                actions={[
                  renderStatusTag(file),
                ]}
              >
                <List.Item.Meta
                  avatar={<FileTextOutlined />}
                  title={<Text>{file.name}</Text>}
                  description={
                    <Text type="secondary">
                      原始名称: {file.originalName}
                      {file.error && ` - 错误: ${file.error}`}
                    </Text>
                  }
                />
              </List.Item>
            )}
          />
        </div>
      )}

      {!isTauriEnvironment && (
        <div style={{ marginTop: '20px', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
          <Text type="secondary">
            注意：在浏览器环境中，此工具仅演示文件名转换效果。要实际重命名文件，请使用桌面应用。
          </Text>
        </div>
      )}
    </Card>
  );
};

export default FileNameProcessor;